package com.iflytek.cosmo.ocr.common.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * Jackson可以序列化抽象类定义
 * 
 * @author ljhan2
 */
public abstract class Jacksonable {

    /**
     * 序列化当前对象为JSON字符串
     * 
     * @return 序列化后的JSON字符串
     * @author ljhan2
     */
    public String toJson() {
        ObjectMapper mapper = ObjcetMapperBean.singletonNativeInstance();
        try {
            return mapper.writeValueAsString(this);
        } catch (Throwable e) {
            throw new JacksonHandleJsonRuntimeException(e.getMessage(), e);
        }
    }

    /**
     * 序列化当前对象为JSON字符串（格式化）
     * 
     * @return 序列化后的JSON字符串（格式化）
     * @author ljhan2
     */
    public String toPrettyJson() {
        ObjectMapper mapper = ObjcetMapperBean.prototypeInstance();
        try {
            ObjcetMapperBean.initNative(mapper);
            mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
            return mapper.writeValueAsString(this);
        } catch (Throwable e) {
            throw new JacksonHandleJsonRuntimeException(e.getMessage(), e);
        }
    }
}
